import { updataLocalCart, mergeCar, getCarList, postCarList, deleteCart ,updataCart, checkAllCart} from "@/api/cart"
// 购物车
export default ({
  namespaced: true,
  state() {
    return {
      list: []
    }
  },
  mutations: {
    insertCart(state, payload) {
      // 查询有没有和goods中skuid相等的，如果没找到返回-1

      const sameIndex = state.list.findIndex(item => item.skuId === payload.skuId)
      if (sameIndex > -1) { // 大于-1证明找到了
        // 如果商品相同则追加数量
        payload.count = state.list[sameIndex].count + payload.count
        // 将相同的删除一个
        state.list.splice(sameIndex, 1)
      }
      // 数量该变后插入到数组最前面
      state.list.unshift(payload)
    },
    //修改本地购物车数据(数量，选中)
    updataLocal(state, goods) {
      console.log(state.list);
      console.log(goods);

      const sameGoods = state.list.find(item => item.skuId === goods.skuId)
      console.log(sameGoods);
      for (let key in goods) {
        if (goods[key] !== null && goods[key] !== undefined && goods[key] !== '') {
          sameGoods[key] = goods[key]
        }
      }

    },
    //删除购物车商品
    deleteGoods(state, skuId) {
      const sameSk = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(sameSk, 1)
    },
    //合并后清空购物车
    setCart(state, payload) {
      state.list = payload
    }
  },
  getters: {
    //挑选出有效商品，库存》0，isEffective有效
    screenGoods(state) {
      return state.list.filter(goods => goods.stock > 0 && goods.isEffective)
    },
    //计算所有商品件数总和
    calculateNumber(state, getters) {
      return getters.screenGoods.reduce((add, cur) => add + cur.count, 0)
    },
    //计算所有价格总和
    claculatePrice(state, getters) {
      return getters.screenGoods.reduce((add, cur) => add + (cur.nowPrice * 100 * cur.count), 0) / 100
    },
    //筛选出无效商品
    invalidGoods(state) {
      return state.list.filter(item => item.count <= 0 && item.isEffective)
    },
    //已选商品
    selectGoods(state, getters) {
      return getters.screenGoods.filter(item => item.selected)
    },
    //已选商品总价格
    selectPrice(state, getters) {
      return getters.selectGoods.reduce((p, c) => p + c.nowPrice * c.count * 100, 0) / 100
    },
    //已选总数量
    selectCount(state, getters) {
      return getters.selectGoods.reduce((p, c) => p + c.count, 0)
    },
    //是否全选
    allSelect(state, getters) {
      return getters.screenGoods.length === getters.selectGoods.length && getters.selectGoods.length !== 0
    }
  },
  actions: {
    //合共购物车
    async mergCar(ctx) {
      const cartList = ctx.state.list.map(item => {
        return {
          skuId: item.skuId,
          selected: item.select,
          count: item.count
        }
      })
      await mergeCar(cartList)
      ctx.commit('setCart', [])
    },
    //加入购物车
    insertCart(ctx, payload) {
      return new Promise((resolve, reject) => {
        // rootState,等同于 `store.state`，只存在于模块中，可以拿到所有模块数据
        if (ctx.rootState.user.profile.token) {
          // 登录
          postCarList({ skuId: payload.skuId, count: payload.count }).then(() => {
            //登录后加入服务端数据，重新拉取服务端数据才会显示
            return getCarList()
          }).then(data => {
            ctx.commit('setCart', data.result)
          })
        } else {
          // 未登录
          console.log(1232434);
          ctx.commit('insertCart', payload)
          resolve()
        }
      })
    },
    //获取购物车商品列表
    getLocaCart(ctx) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          //已登录
          getCarList().then(data => {
            ctx.commit('setCart',data.result )
            resolve()
          })
        } else {
          //未登录
          console.log(1232434);
          console.log(ctx);
          const promiseArry = ctx.state.list.map(item => {
            return updataLocalCart(item.skuId)
          })
          console.log(promiseArry);
          Promise.all(promiseArry).then(dataArry => {
            console.log(dataArry);
            dataArry.forEach((data, i) => {
              ctx.commit('updataLocal', { skuId: ctx.state.list[i].skuId, ...data.result })
              resolve()
            })

          }).catch(e => {
            reject(e)
          })
        }
      })
    },
    //删除本地购物车
    deleteCart(ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          deleteCart([payload]).then(() => {
            return getCarList()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          //未登录
          //payload是skuId
          ctx.commit('deleteGoods', payload)
          resolve()
        }
      })
    },
    //修改更新购物车选中状态，和数量
    updataCar(ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          //已登录
          updataCart(payload).then(()=>{
           return  getCarList()
          }).then(data=>{
            ctx.commit('setCart',data.result)
            resolve()
          })
        } else {
          //未登录
          ctx.commit('updataLocal', payload)
          resolve()
        }
      })
    },
    //全选
    checkAll(ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          //已登录
          const ids=ctx.getters.screenGoods.map(item=>item.skuId)
          checkAllCart({selected,ids}).then(()=>{
            return getCarList()
          }).then(data=>{
            ctx.commit('setCart',data.result)
            resolve()
          })
          console.log(selected);
        } else {
          //未登录
          ctx.getters.screenGoods.forEach(item => {
            ctx.commit('updataLocal', { skuId: item.skuId, selected })
            resolve()
          })

        }
      })
    },
    //全删
    allDelete(ctx, isClear) {
      console.log(isClear);
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          const ids=ctx.getters[isClear ? 'invalidGoods' : 'selectGoods'].map(item=>item.skuId)
          deleteCart(ids).then(()=>{
            return getCarList()
          }).then(data=>{
            ctx.commit('setCart',data.result)
            resolve()
          })
        } else {
          //未登录
          ctx.getters[isClear ? 'invalidGoods' : 'selectGoods'].forEach(item => {

            ctx.commit('deleteGoods', item.skuId)
            resolve()
          })
        }
      })
    },
    //更新购物车中商品规格skuId
    updataCarSkuId(ctx, { newskuId, oldSkuId }) {
      console.log(oldSkuId)
      console.log(newskuId.value)
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          deleteCart([oldGoods.skuId]).then(()=>{
           return postCarList({skuId:newskuId.value.skuId,count:oldGoods.count})
          }).then(
            ()=>{
              return getCarList()
            }
          ).then(data=>{
            ctx.commit('setCart',data.result)
            resolve()
          })
        } else {
          //未登录
          /*找出新的skuId和旧的skuId相等的商品列表返回
           删除旧的商品列表
           将旧商品列表数据替换为新的商品数据
           commit提交更新商品mutations方法*/
           console.log(newskuId);
           console.log(oldSkuId);
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          ctx.commit('deleteGoods', oldSkuId)
          const { skuId, price: nowPrice, specsText: attrsText, inventory: stock } = newskuId.value
          console.log(skuId);
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock }
          ctx.commit('insertCart', newGoods)
          resolve()
          //  const newGoods={...oldSkuIdGoods,stock,oldPrice,nowPrice,skuId,attrsText}
          //   ctx.commit('insertCart',newGoods)
          // resolve()
        }
      })

    }
  },
})
